const path = require("path");
const fs = require("fs");

//文件是否存在
function dirExists(path) {
	try {
		const dirent = fs.accessSync(savePath);
		return dirent.isDirectory();
	} catch (e) {
		return false;
	}
}

//文件探测回调
function detectDir(path, success, fail) {
	const existStatus = dirExists(path);
	if (!existStatus) {
		fs.mkdirSync(path, { recursive: true });
		success && success();
	} else {
		fail && fail();
	}
}

//存储文件
function saveFile(savePath, filename, content) {
	const fullpath = path.join(savePath, filename);
	try {
		fs.writeFileSync(fullpath, content);
	} catch (e) {
		//savePath文件保存路径可能不存在
		detectDir(savePath, () => {
			fs.writeFileSync(fullpath, content);
		});
	}
	return fullpath;
}

//读取文件
function readFile(filepath, filename) {
	const fullpath = path.join(filepath, filename); //完整路径
	const content = fs.readFileSync(fullpath); //获取内容
	return content;
}

// 删除文件
function delFile(target) {
	try {
		return fs.unlinkSync(target);
	} catch (e) {
		console.log("你要删除的文件不存在");
	}
}

//获取随机名
function randomFileName(filename) {
	return  +(new Date()) + "_" + (filename || '')
}

module.exports = {
	delFile,
	readFile,
	saveFile,
	randomFileName
}